package org.boot.fast.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.boot.fast.pojo.CommonResult;
import org.boot.fast.pojo.FileInfoDO;
import org.boot.fast.service.FileUploadService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import java.util.Arrays;
import java.util.List;

import static org.boot.fast.pojo.CommonResult.success;


@Tag(name = "文件基础功能管理")
@RestController
@RequestMapping("/fast/file")
public class FileUploadController {

    @Resource
    private FileUploadService fileInfoService;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @Operation(summary = "文件上传")
    public CommonResult<Long> upload(@RequestParam("file") MultipartFile file,
                                     @RequestParam(value = "uploadUser", required = false) String uploadUser) {
        return success(fileInfoService.upload(file, uploadUser).getId());
    }

    /**
     * 批量文件上传
     * @param files       多文件
     * @param uploadUser  上传人（仍用字符串，可复用原字段）
     * @return 返回所有成功文件的 id 列表
     */
    @PostMapping("/uploadBatch")
    @Operation(summary = "批量文件上传")
    public CommonResult<List<Long>> uploadBatch(@RequestParam("files") MultipartFile[] files,
                                                @RequestParam(value = "uploadUser", required = false) String uploadUser) {
        // 参数快速校验
        if (files == null || files.length == 0) {
            return CommonResult.error("请至少选择一个文件");
        }
        List<Long> ids = fileInfoService.uploadBatch(Arrays.asList(files), uploadUser);
        return CommonResult.success(ids);
    }

    /**
     * 文件删除0
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    @Operation(summary = "文件删除")
    public CommonResult<Boolean> delete(@RequestParam("id") Long id) {
        return success(fileInfoService.delete(id));
    }

    /**
     * 文件下载
     * @param id
     * @param response
     */
    @GetMapping("/download")
    @Operation(summary = "文件下载")
    public void download(@RequestParam("id") Long id, HttpServletResponse response) {
        fileInfoService.download(id, response);
    }

    /**
     * 文件预览
     * @param id
     * @param response
     */
    @GetMapping("/preview")
    @Operation(summary = "文件预览")
    public void preview(@RequestParam("id") Long id, HttpServletResponse response) {
        fileInfoService.preview(id, response);
    }

}
